package com.example.usbhidtool.tcp;

import android.annotation.SuppressLint;
import android.util.Log;

import com.easysocket.EasySocket;
import com.easysocket.entity.OriginReadData;
import com.easysocket.entity.SocketAddress;
import com.google.gson.JsonObject;

import java.util.Base64;

public class HidMessageHandle {
    static int Lastlength = 0;

    /**
     * 处理服务器发送过来的消息
     */
    @SuppressLint("NewApi")
    public static void handleMessage(SocketAddress socketAddress, OriginReadData originReadData, SocketMsgCallBack callBack) {
        try {
            if (originReadData == null) {
                Log.e("SOCKET", "数据位空");
            } else {
                //处理数据
                byte[] bytearr = originReadData.getOriginDataBytes();
                if (bytearr.length == 4) {
                    for (int i = 0; i < 4; i++) {
                        int shift = i * 8;
                        Lastlength += (bytearr[i] & 0xFF) << shift;
                    }
                }
                if (Lastlength != 0 && bytearr.length == Lastlength)//判断长度为84时发送授权数据到盒子
                {
                    JsonObject json = new JsonObject();
                    json.addProperty("type", "authorized");
                    json.addProperty("data", Base64.getEncoder().encodeToString(bytearr));
                    byte[] send = json.toString().getBytes("UTF-8");
                    callBack.onSendData(send);
//                    MainActivity.getInstance().sendDataMsg(send);
                    Lastlength = 0;
                    if (bytearr.length > 84) {
                        EasySocket.getInstance().getSpecifyConnection(socketAddress.getIp() + ":" + socketAddress.getPort()).disconnect(false);
//                        EasySocket.getInstance().disconnect(socketAddress.getIp() + ":" + socketAddress.getPort(), false);
                    }
                }
                callBack.onPrintLog("SOCKET:获取到服务器消息:len=>" + bytearr.length + " Lastlength=>" + Lastlength);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface SocketMsgCallBack {

        void onSendData(byte[] data);

        void onPrintLog(String log);
    }
}
